using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using TanashCMS.Business;
using System.Text;

public partial class manager_inventory_InventoryUpdate : CMSManagementPageBase
{
    protected override void OnInit(EventArgs e)
    {
        
        base.OnInit(e);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnGenerateCSV_Click(object sender, EventArgs e)
    {
        int websiteid = (int)Profile.GetPropertyValue("WebsiteID");
        if (mWebsite != null)
            websiteid = mWebsite.ID;

        string file = InventoryIO.WriteInventoryToCSVFile(websiteid);

        Response.Redirect(file);

    }
    protected void btnUploadDataFile_Click(object sender, EventArgs e)
    {
        if (uploadInventory.PostedFile != null)
        {
            HttpPostedFile file = uploadInventory.PostedFile;

            int fileLength = file.ContentLength;
            byte[] fileData = new byte[fileLength];
            file.InputStream.Read(fileData, 0, fileLength);

            string fileName = Guid.NewGuid().ToString();
            string path = Server.MapPath("~/import/"+mWebsite.SubFolderName+"/").TrimEnd('\\') + @"\";

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            while (File.Exists(path + fileName))
                fileName = Guid.NewGuid().ToString();

            FileStream fstream = new FileStream(path + fileName, FileMode.CreateNew);

            fstream.Write(fileData, 0, fileLength);

            fstream.Close();
            int websiteid = (int)Profile.GetPropertyValue("WebsiteID");
            if (mWebsite != null)
                websiteid = mWebsite.ID;

            litDataFileID.Text = path + fileName;

            // create a new inventory import
            /*
            InventoryImport importBatch = new InventoryImport();
            importBatch.WebsiteID = websiteid;
            importBatch.CSVFileName = fileName;
            importBatch.DateCreated = DateTime.Now;
            importBatch.Status = ImportStatus.New;
            Configuration.GetCurrentSession().Save(importBatch);
            */

            int goodRows=0, badRows=0;
            InventoryIO.ImportRow[] rowResults = InventoryIO.ParseInventoryUploadFile(path + fileName, websiteid, out goodRows, out badRows);

            StringBuilder sbResultsOverview = new StringBuilder();
            StringBuilder sbSuccessItems = new StringBuilder();
            StringBuilder sbErrorItems = new StringBuilder();
            StringBuilder sbCategories = new StringBuilder();
            List<string> foundCategories = new List<string>();
            

            sbResultsOverview.Append("<div id='resultsOverview'><h2>");
            sbResultsOverview.Append(string.Format("Ready to Import - {0} rows parsed ({1} errors)",rowResults.Length,badRows));
            sbResultsOverview.Append("</h2>");
            sbResultsOverview.Append("<p><strong>If you choose to import this file, rows containing errors will be ignored.</strong></p>");
            sbResultsOverview.Append("</div>");

            litResultsOverview.Text = sbResultsOverview.ToString();

            sbSuccessItems.Append("<a name='success'></a><ul id='resultsSuccess' class='importresults' style='display:none;'><li>Click a row to view details</li>");
            sbErrorItems.Append("<a name='errors'></a><ul id='resultsErrors' class='importresults'><li>Click a row to view details</li>");
            if (badRows == 0)
                sbErrorItems.Append("No errors found");
            sbCategories.Append("<a name='categories'></a><ul id='resultsCategories' class='importresults' style='display:none;'><li>The following categories were found in the data file:</li>");

            foreach (InventoryIO.ImportRow row in rowResults)
            {
                StringBuilder sb =null;
                if (row.HasError)
                    sb = sbErrorItems;
                else
                    sb = sbSuccessItems;

                sb.Append("<li ");
                if (row.HasError)
                    sb.Append("class='importrow erRow'>");
                else
                    sb.Append("class='importrow'>");

                sb.Append("<div class='rownum'><a class='importrowlink' href='javascript:void(0);' onclick='showhide(\"results"+row.RowNumber.ToString()+"\");'>Row "+(row.RowNumber+1).ToString()+"</a></div>\n");
                sb.Append("<div class='results' style='display:none;' id='results" + row.RowNumber.ToString() + "'>");
                foreach (InventoryIO.RowMessage message in row.Messages)
                {
                    HtmlGenericControl resultMessage = new HtmlGenericControl("div");
                    sb.Append("<div ");
                    
                    if (message.HasError)
                        sb.Append("class='message erMessage'>");
                    else
                        sb.Append("class='message'>");
                    sb.Append(message.Message);
                    
                    sb.Append("</div>");
                }
                sb.Append("</div>");
                sb.Append("</li>\n");

                if (!foundCategories.Contains(row.CategoryName))
                {
                    foundCategories.Add(row.CategoryName);
                    sbCategories.Append("<li");
                    if (row.CategoryID == 0)
                        sbCategories.Append(" class='newcategory'");
                    sbCategories.Append(">" + row.CategoryName);
                    if (row.CategoryID == 0)
                        sbCategories.Append(" (New Category)");
                    sbCategories.Append("</li>");
                }
            }
            sbSuccessItems.Append("</ul>");
            sbErrorItems.Append("</ul");
            sbCategories.Append("</div>");

            litResults.Text += "<div class=\"toolbar\">" +
                "<span class=\"tab active\" id=\"tabErrors\"><a href=\"javascript:void(0);\" onclick=\"tab('tabErrors','resultsErrors');\">";
            litResults.Text += string.Format("Errors ({0})",badRows);
            litResults.Text += "</a></span><span class=\"tab\" id=\"tabSuccess\"><a href=\"javascript:void(0);\" onclick=\"tab('tabSuccess','resultsSuccess');\">";
            litResults.Text += string.Format("Successful ({0})", goodRows);
            litResults.Text += "</a></span><span class=\"tab\" id=\"tabCategories\"><a href=\"javascript:void(0);\" onclick=\"tab('tabCategories','resultsCategories');\">Categories</a></span></div>";

            litResults.Text += sbErrorItems.ToString();
            litResults.Text += sbSuccessItems.ToString();
            litResults.Text += sbCategories.ToString();

            panelImport.Visible = true;
            panelSelectFile.Visible = false;

            /*
            InventoryIO.UpdateProductInventory(path + fileName, websiteid);
            Response.Redirect("~/manager/inventory/?sf=" + Server.UrlEncode("The file has been queued for processing."), true);
             * */

        }
    }

    protected void btnUpdateInventory_Click(object sender, EventArgs e)
    {
        string datafilename = litDataFileID.Text;
        /*

        int goodRows = 0, badRows = 0;
        InventoryIO.ImportRow[] rowResults = InventoryIO.ParseInventoryUploadFile(datafilename, mWebsite.ID, out goodRows, out badRows);

        StringBuilder sb = new StringBuilder();

        litResults.Text="<textarea style='width:100%;height:600px;'>";
        litResults.Text += "begin transaction\n";
        litResults.Text += "update Product set Product.State = " + ((int)CMSObjectState.Deleted).ToString() + " where Product.WebsiteID = " + mWebsite.ID.ToString() + "\n";
        litResults.Text += "update Category set Category.State = " + ((int)CMSObjectState.Deleted).ToString() + " where Category.WebsiteID = " + mWebsite.ID.ToString() + "\n";

        foreach (InventoryIO.ImportRow row in rowResults)
        {
            if (!row.HasError)
                sb.Append(row.SQLCommandText);
        }
        litResults.Text += sb.ToString();

        litResults.Text += "delete from Product where Product.WebsiteID = " + mWebsite.ID.ToString() + " and Product.State = 2\n";
        litResults.Text += "delete from Category where Category.WebsiteID = " + mWebsite.ID.ToString() + " and Category.State = 2\n";

        litResults.Text += "</textarea>";
         * */

        InventoryIO.UpdateProductInventory(datafilename, mWebsite.ID);
        mWebsite.NeedsPublish = true;
        Configuration.GetCurrentSession().Save(mWebsite);

        Response.Redirect("~/manager/inventory/?sf=" + Server.UrlEncode("The file has been processed."), true);
    }
}
